import modelEnhance from '@/utils/modelEnhance';
import PageHelper from '@/utils/pageHelper';

import { getRoleList } from "../service";

import config from '../../../config.js';

const noticeGlobal = config.notice;

/**
 * 当第一次加载完页面时为true
 * 可以用这个值阻止切换页面时
 * 多次初始化数据
 */
let LOADED = false;
export default modelEnhance({
  namespace: 'roles',

  state: {
    pageData: PageHelper.create(),
    permissionList: [],
    permissionCheckedKeys: [],
    t_permissionCheckedKeys: [],
    menuList: [],
    menuCheckedKeys: [],
    t_menuCheckedKeys: []
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/roles' && !LOADED) {
          LOADED = true;
          dispatch({
            type: 'init'
          });
        }
      });
    }
  },

  effects: {
    // 进入页面加载
    *init({ payload }, { call, put, select }) {
      const { pageData } = yield select(state => state.roles);
      yield put({
        type: 'getPageInfo',
        payload: {
          pageData: pageData.startPage(1, 10)
        }
      });
      yield put({
        type: '@request',
        payload: {
          actionType: 'getPermissionList',
          method: 'GET',
          url: '/api/authManage/permission/permissionTree'
        },
      })
      yield put({
        type: '@request',
        payload: {
          actionType: 'getMenuList',
          method: 'GET',
          url: '/api/authManage/menu/menuTree'
        },
      })
    },
    // 获取分页数据
    *getPageInfo({ payload }, { call, put }) {
      const { pageData } = payload;
      // const {code, msg, data} = yield call(getRoleList, {pageNo: pageData.pageNum, pageSize: pageData.pageSize});
      const {code, msg, data} = yield call(getRoleList, pageData.pageinfoData());
      if (code == 200){
        yield put({
          type: 'setRoleList',
          payload: data
        })
      }else{
        noticeGlobal.error(msg);
      }
    },
    // 保存 之后查询分页
    *save({ payload }, { call, put, select, take }) {
      const { values, success } = payload;
      const { pageData } = yield select(state => state.roles);
      // put是非阻塞的 put.resolve是阻塞型的
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/authManage/role/addNew',
          data: values
        },
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 修改
    *update({ payload }, { call, put, select }) {
      const { values, success } = payload;
      const {pageData} = yield select(state => state.roles);

      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/authManage/role/update',
          data: values
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 删除 之后查询分页
    *remove({ payload }, { call, put, select }) {
      const { records, success } = payload;
      const { pageData } = yield select(state => state.roles);
      yield put({
        type: '@request',
        payload: {
          method: 'DELETE',
          notice: true,
          url: '/api/authManage//role/delete/roleIds',
          data: {idList : records.map(item => item.id)}
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 根据 roleid 获取权限列表
    *getPermissionKeys({payload}, {call, put}){
      const { record, success } = payload;
      yield put.resolve({
        type: '@request',
        payload: {
          actionType: 'setPermissionKeys',
          url: '/api/authManage/permission/byRoleIds',
          data: {"idList": [record.id]}
        },
      })
      success()
    },
    *updatePermissionKeys({payload}, {call, put}){
      const { keys } =payload;
      yield put({
        type: 'setPermissionKeys',
        payload: keys,
      })
    },
    *submitPermisssionKeys({payload}, {call, put, select}){
      const {success, record} = payload;
      const {permissionCheckedKeys, t_permissionCheckedKeys} = yield select(state => state.roles);
      const minus_permissionCheckedKeys = t_permissionCheckedKeys.filter(v=> {return permissionCheckedKeys.indexOf(v) == -1});
      if(permissionCheckedKeys.length > 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/role/assignPermissions',
            data: permissionCheckedKeys.map(item=> {return {permissionId: item, roleId: record.id }})
          }
        });
      }
      if(minus_permissionCheckedKeys.length> 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/role/unassignPermissions',
            data: minus_permissionCheckedKeys.map(item=> {return {permissionId: item, roleId: record.id }})
          }
        });
      }
      success();
    },
    // 根据 roleid 获取菜单列表
    *getMenuKeys({payload}, {call, put}){
      const { record, success } = payload;
      yield put.resolve({
        type: '@request',
        payload: {
          actionType: 'setMenuKeys',
          url: '/api/authManage/menu/byRoleIds',
          data: {"idList": [record.id]}
        },
      })
      success();
    },
    *updateMenuKeys({payload}, {call, put}){
        const { keys } =payload;
        yield put({
          type: 'setMenuKeys',
          payload: keys,
        })
    },
    *submitMenuKeys({payload}, {call, put, select}){
      const {success, record} = payload;
      const {menuCheckedKeys, t_menuCheckedKeys} = yield select(state => state.roles);
      const minus_menuKeys = t_menuCheckedKeys.filter(function(v){ return menuCheckedKeys.indexOf(v) == -1 });
      if(menuCheckedKeys.length > 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/role/assignMenus',
            data: menuCheckedKeys.map(item=> {return {menuId: item, roleId: record.id }})
          }
        });
      }
      if(minus_menuKeys.length > 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/role/unassignMenus',
            data: minus_menuKeys.map(item=> {return {menuId: item, roleId: record.id }})
          }
        })
      };
      success();
    }
  },

  reducers: {
    setRoleList(state, {payload}){
      const { pageData } = state;
      return {
        ...state,
        pageData: pageData.setPage({data: payload}),
      }
    },
    getPermissionList_SUCCESS(state, {payload}){
      return {
        ...state,
        permissionList: config.tranferTreeData(payload.data, 'id', 'permissionDescription'),
      }
    },
    getMenuList_SUCCESS(state, {payload}){
      return {
        ...state,
        menuList: config.tranferTreeData(payload.data, 'id', 'name')
      }
    },
    setPermissionKeys_SUCCESS(state, {payload}){
      return {
        ...state,
        permissionCheckedKeys: payload.data.map(item=> item.id),
        t_permissionCheckedKeys: payload.data.map(item=> item.id)
      }
    },
    setPermissionKeys(state, {payload}){
      return {
        ...state,
        permissionCheckedKeys: payload
      }
    },
    setMenuKeys_SUCCESS(state, {payload}){
      return {
        ...state,
        menuCheckedKeys: payload.data.map(item=> item.id),
        t_menuCheckedKeys: payload.data.map(item=> item.id)
      }
    },
    setMenuKeys(state, {payload}){
      return {
        ...state,
        menuCheckedKeys: payload
      }
    }
  }
});
